package org.frog.sgs.server;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.Scanner;

import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.frog.sgs.card.Card;
import org.frog.sgs.consts.Constants;
import org.frog.sgs.data.GameDataManager;
import org.frog.sgs.io.SgsCodecFactory;
import org.frog.sgs.server.game.ServerInstance;

/**
 * @author duanxiangqi
 * @date 2012-10-19
 */
public class SgsServer {

	public static void main(String[] args) throws Exception {
		new SgsServer().startup();
	}

	private ServerInstance instance;

	private NioSocketAcceptor acceptor;

	public void startup() throws Exception {
		System.out.println("====================================");
		System.out.println(Card.VERSION);
		System.out.println("====================================");
		GameDataManager.instance.init();
		Map<Integer, ServerConfig> configs = GameDataManager.instance.getAllGameConfigs();
		for (ServerConfig config : configs.values()) {
			System.out.print("[" + config.getId() + "：" + config.getName() + "(" + config.getPlayerNum() + ")]；");
		}
		System.out.println();
		System.out.println("请选择对战模式，输入ID：");
		Scanner scanner = new Scanner(System.in);
		ServerConfig config = null;
		while (true) {
			// TODO int configId = scanner.nextInt();
			int configId = 2;
			config = configs.get(configId);
			if (config != null) {
				scanner.close();
				break;
			} else {
				System.err.println("无效的对战模式ID：" + configId);
			}
		}
		System.out.println("已选择对战模式：[" + config.getId() + "：" + config.getName() + "]。");

		instance = new ServerInstance(config);
		instance.init();

		acceptor = new NioSocketAcceptor(1);// 单线程 保证 同步 以后修改
		ServerIoHandler ioHandler = new ServerIoHandler();
		ioHandler.setServer(this);

		acceptor.setHandler(ioHandler);
		acceptor.getSessionConfig().setKeepAlive(false);
		acceptor.getSessionConfig().setReadBufferSize(Constants.SERVER_SESSION_BUFFER_SIZE);// 发送缓冲区10M
		acceptor.getSessionConfig().setReceiveBufferSize(Constants.SERVER_SESSION_BUFFER_SIZE);// 接收缓冲区10M

		ProtocolCodecFactory codecFactory = new SgsCodecFactory();
		acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(codecFactory));

		acceptor.bind(new InetSocketAddress(Constants.SERVER_PORT));
		System.out.println("服务器启动完毕，监听端口：" + Constants.SERVER_PORT);
		System.out.println("等待玩家加入。。。");
	}

	public void stop() {
		System.exit(0);
	}

	public NioSocketAcceptor getAcceptor() {
		return acceptor;
	}

	public ServerInstance getInstance() {
		return instance;
	}
}
